/**
 * 
 */
package com.ginger.rabbitmq.exchange.api.direct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ginger.properties.RabbitMQProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

/**
 * @Description:消费者
 * @author 姜锋
 * @date 2019年3月29日 上午9:40:24
 * @version V1.0
 */
public class Consumer4DirectExchange {
	/** 日志对象 **/
	private final static Logger logger = LoggerFactory.getLogger(Consumer4DirectExchange.class);
	
	public static void main(String[] args) throws Exception{
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		
		//1.1设置连接信息
		connectionFactory.setHost(RabbitMQProperties.RABBITMQ_HOST);
		connectionFactory.setPort(RabbitMQProperties.RABBITMQ_PORT);
		connectionFactory.setVirtualHost(RabbitMQProperties.RABBITMQ_VIRTUAL_HOST);
		connectionFactory.setUsername(RabbitMQProperties.USER_NAME);
		connectionFactory.setPassword(RabbitMQProperties.PASSWORD);
		
		//是否支持自动重连
		connectionFactory.setAutomaticRecoveryEnabled(true);
		//重连设置
		connectionFactory.setNetworkRecoveryInterval(3000);
		// 2.通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		// 3.通过connection创建
		Channel channel = connection.createChannel();
		
		//4.申明
		String exchangeName = "test_direct_exchange";
		String exchangeType = "direct";
		String queueName = "test_direct_queue";
		String routingKey = "test.direct";
		
		//声明交换机
		//channel.exchangeDeclare(交换机名称, 交换机类型,是否持久化,是否自动删除,扩展参数);
		channel.exchangeDeclare(exchangeName, exchangeType,true,false,null);
		
		//申明一个队列
		//channel.queueDeclare(队列名称,是否持久化,是否独占,脱离绑定关系是否自动删除,扩展参数)
		channel.queueDeclare(queueName,true,false,false,null);
		
		//对交换机与队列建立绑定
		//channel.queueBind(队列名称, 交换机名称, routingKey);
		channel.queueBind(queueName, exchangeName, routingKey);
		
		//5.创建消费者
		QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
		
		//6.设置channel
		//channel.basicConsume(队列名称,自动签收,消费者对象);
		channel.basicConsume(queueName, true,queueingConsumer);
		
		while (true) {
			//7.获取消息
			Delivery delivery = queueingConsumer.nextDelivery();
			String msg = new String(delivery.getBody());
			logger.info("消费端接收内容: -->"+msg);
			//Envelope envelope= delivery.getEnvelope();
		}
	}
}
